# -*- coding:utf-8 -*-
import ConfigParser,time
import httplib,urllib,urllib2,json
import socket,hashlib
import qutils

def httpSMS(aPn, aCode):

    tmpPn = str(aPn)
    tmpCode = str(aCode)
    qutils.rctLogger.info("pn=%s,code=%s" % (tmpPn,tmpCode))
    tmpPath = "/sms/send?mobile="
    tmpPath += tmpPn
    tmpPath += "&tpl_id=21768&tpl_value=%23code%23%3d"
    tmpPath += tmpCode
    tmpPath += "&dtype=json&key=8b09560bf322c515a75730bf982d5957"
    conn = httplib.HTTPConnection("v.juhe.cn")
    conn.request("GET", tmpPath)
    r1 = conn.getresponse()
    #print r1.status, r1.reason
    tmpRsp = r1.read()
    conn.close()
    
    qutils.rctLogger.info("----------rsp=%s" % (tmpRsp))
    if(r1.status != 200):
        return None
        
    if(not tmpRsp) or (len(tmpRsp) <= 0):
        return None
        
    tmpJson = json.loads(tmpRsp)
    if(not tmpJson):
        return None
        
    if(not tmpJson.has_key('error_code')):
        return None
        
    if(tmpJson['error_code'] != 0):
        return None
        
    return tmpRsp

def writeToConfig (aCard, aCode):

    tmpCard = str(aCard)
    tmpCode = str(aCode)

    tmpConfig = ConfigParser.ConfigParser()
    tmpConfig.read("code.config")
    tmpSections = tmpConfig.sections()

    if not tmpSections or len(tmpSections) <= 0:
        addSecion(tmpCard, tmpCode, tmpConfig)
        return

    if tmpCard in tmpSections:
        updateSection(tmpCard, tmpCode, tmpConfig)
        return
    addSecion(tmpCard, tmpCode, tmpConfig)

def updateSection (aCard, aCode, aConfig):
    aConfig.set(aCard, 'card', aCard)
    aConfig.set(aCard, 'code', aCode)
    aConfig.set(aCard, 'time', int(time.time()))
    aConfig.write(open("code.config", "w"))

def addSecion (aCard, aCode, aConfig):
    aConfig.add_section(aCard) 
    aConfig.set(aCard, 'card', aCard)
    aConfig.set(aCard, 'code', aCode)
    aConfig.set(aCard, 'time', int(time.time()))
    aConfig.write(open("code.config", "w"))

def shouldSendNew (aCard,aTime):
    tmpCard = str(aCard)
    tmpTime = int(aTime)
    tmpConfig = ConfigParser.ConfigParser()
    tmpConfig.read("code.config")
    tmpSections = tmpConfig.sections()
    
    if not tmpSections or len(tmpSections) <= 0:
        return True

    if tmpCard in tmpSections:
        tmpTimeLast = int(tmpConfig.get(tmpCard,"time"))
        if tmpTime - tmpTimeLast < 300:
            return False
        tmpConfig.remove_section(tmpCard)
        tmpConfig.write(open("code.config", "w"))
    return True

def isCodeCorrect (aCard, aCode):
    tmpCard = str(aCard)
    tmpCode = str(aCode)
    tmpConfig = ConfigParser.ConfigParser()
    tmpConfig.read("code.config")
    tmpSections = tmpConfig.sections()

    if tmpCard in tmpSections:
        tmpCodeSave = tmpConfig.get(tmpCard, "code")
        if qutils.isEmpty(tmpCodeSave):
            return False
        if tmpCode != tmpCodeSave:
            return False
        return True
    return False








